package morningcat.demo2.durable;

import com.rabbitmq.client.*;
import morningcat.MQParams;

/**
 * XXX
 *
 * @author mengzhang6
 * @date 2018/12/17 9:45
 */
public class Consumer {

    public static void main(String[] argv) throws Exception {
        // ConnectionFactory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(MQParams.SERVER_HOST);
        factory.setPort(MQParams.SERVER_PORT);

        // 连接
        Connection connection = factory.newConnection();

        // 信道
        Channel channel = connection.createChannel();
        channel.queueDeclare(MQParams.QUEUE_NAME_DURABLE, true, false, false, null);
        channel.basicQos(1);
        System.out.println(" [*] Waiting for messages. 消费者");

        // DeliverCallback
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("consumerTag:" + consumerTag);
            System.out.println(" [x] Received '" + message + "'");

            try {
                doWork(message);
            } finally {
                System.out.println(" [x] Done");
            }
        };

        // CancelCallback
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("cancelCallback consumerTag:" + consumerTag);
        };

        // 订阅消息
        channel.basicConsume(MQParams.QUEUE_NAME_DURABLE, true, deliverCallback, cancelCallback);
    }

    private static void doWork(String message) {

        System.out.println(message + " 处理完成");
    }
}
